package org.example.flea_market_mvc.controller;

import org.example.flea_market_mvc.entity.Ratings;
import org.example.flea_market_mvc.param.RatingParam;
import org.example.flea_market_mvc.service.ratings.RatingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/ratings")
@Validated
public class RatingsController {

    @Autowired
    private RatingsService ratingsService;

    @PostMapping
    public ApiResponse<String> addRating(@Valid @RequestBody RatingParam ratingParam) {
        int result = ratingsService.insert(ratingParam);
        return result > 0 ? ApiResponse.success("添加评价成功") : ApiResponse.error(400, "添加评价失败");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteRating(@PathVariable Integer id) {
        int result = ratingsService.deleteById(id);
        return result > 0 ? ApiResponse.success("删除评价成功") : ApiResponse.notFound("评价不存在");
    }

    @PutMapping
    public ApiResponse<String> updateRating(@Valid @RequestBody RatingParam ratingParam) {
        int result = ratingsService.update(ratingParam);
        return result > 0 ? ApiResponse.success("修改评价成功") : ApiResponse.notFound("评价不存在");
    }

    @GetMapping("/{id}")
    public ApiResponse<Ratings> getRating(@PathVariable Integer id) {
        Ratings rating = ratingsService.selectById(id);
        return rating != null ? ApiResponse.success(rating) : ApiResponse.notFound("评价不存在");
    }

    @GetMapping
    public ApiResponse<List<Ratings>> getAllRatings() {
        List<Ratings> ratings = ratingsService.selectAll();
        return ApiResponse.success(ratings);
    }

    /**
     * 查询用户平均评分（用于商品详情页展示卖家星级）
     */
    @GetMapping("/user/{userId}/average")
    public ApiResponse<Double> getUserAverageRating(@PathVariable Integer userId) {
        Double avg = ratingsService.getUserAverageRating(userId);
        return ApiResponse.success(avg);
    }
}